package com.spring.demo10.eg3;


import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author vhans
 */
public class BeanRefreshScope implements Scope {
    public static final String SCOPE_REFRESH = "refresh";

    private static final BeanRefreshScope INSTANCE = new BeanRefreshScope();

    // 用个Map来缓存bean
    private ConcurrentHashMap<String, Object> beanMap = new ConcurrentHashMap<>();

    public BeanRefreshScope() {
    }

    public static BeanRefreshScope getInstance() {
        return INSTANCE;
    }

    // 清理作用域中的beanMap当前已缓存的所有bean缓存
    public static void clean() {
        INSTANCE.beanMap.clear();
    }

    @Override
    public Object get(String s, ObjectFactory<?> objectFactory) {
        // 先从beanMap中获取，获取不到会调用objectFactory的getObject让spring创建bean的实例，然后加到beanMap中
        Object bean = beanMap.get(s);
        if (bean == null) {
            bean = objectFactory.getObject();
            beanMap.put(s, bean);
        }
        return bean;
    }

    @Override
    public Object remove(String s) {
        return null;
    }

    @Override
    public void registerDestructionCallback(String s, Runnable runnable) {

    }

    @Override
    public Object resolveContextualObject(String s) {
        return null;
    }

    @Override
    public String getConversationId() {
        return null;
    }
}
